package com.neusoft.neuiotms.dcom.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.dto.DictionaryDTO;
import com.neusoft.neuiotms.common.service.DictionaryService;
import com.neusoft.neuiotms.dcom.constants.DCOMConstants;
import com.neusoft.neuiotms.dcom.model.InspectionTask;
import com.neusoft.neuiotms.dcom.model.enums.InspectionTaskStatus;
import com.neusoft.neuiotms.dcom.repository.InspectionTaskRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * 用来设置巡检任务状态 1.超过计划结束时间未领取的 InspectionTaskStatus.overtime, 2.超过计划结束时间n小时的
 * InspectionTaskStatus.overtimeUnfinished,
 */
@Slf4j
@Component
public class InspectionStatusTask {

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private InspectionTaskRepository inspectionTaskRepository;

    @Scheduled(cron = "0 0 0 * * ?")
    protected void executeInternal() {
        InspectionStatusTask.log.info("定时----检查每个巡检任务的状态");
        final Date now = new Date();
        final List<DictionaryDTO> dicts =
                this.dictionaryService.findByDictionaryType(DCOMConstants.INSPECTION_OVERTIME_TYPE);
        double difference = 24 * 3600 * 1000;
        if ((dicts != null) && !dicts.isEmpty()) {
            try {
                difference = Double.valueOf(dicts.get(0).getText()) * 3600 * 1000;
            } catch (final Exception e) {
                InspectionStatusTask.log.error("超时时间设置有误，使用默认时间（24h）");
            }
        }

        //标记是否修改
        final List<InspectionTask> saveLists = new ArrayList<>();
        final Searchable searchable = new Searchable();
        final String[] status = {InspectionTaskStatus.notStarted.name(), InspectionTaskStatus.inspecting.name() };
        searchable.put("multiStatus", status);
        final List<InspectionTask> lists = this.inspectionTaskRepository.index(searchable);
        for (final InspectionTask i : lists) {
            if (i.getStatus() == InspectionTaskStatus.notStarted) {
                if (now.getTime() > i.getEndTaskTime().getTime()) {
                    i.setStatus(InspectionTaskStatus.overtime);
                    saveLists.add(i);
                }
            } else {
                if ((now.getTime() - i.getEndTaskTime().getTime()) > difference) {
                    i.setStatus(InspectionTaskStatus.overtimeUnfinished);
                    saveLists.add(i);
                }
            }
        }
        if (!saveLists.isEmpty()) {
            this.inspectionTaskRepository.saveAll(saveLists);
        }
        InspectionStatusTask.log.info("定时----检查每个巡检任务的状态");
    }

}
